
from flask import Blueprint
from app.libs.exception import Forbidden, ServerError, Success

from app.libs.forms import CreateResourcePureForm, IDForm, ResourceByIDForm, GetResourceListForm, SearchForm, TypeForm, GetOneByUrlForm, UploadByPathForm, UploadPureVideoForm, UploadPureVideoForm, VSConfigForm
from app.libs.enums import RType
from app.service.course import CourseService
from app.service.video import VideoService
from app.service.chapter import ChapterService
from app.vo import ChapterPureListVO, ChapterVO, CoursePureListVO, CourseVO, CreatePureVO, SChapterVO, SCourseVO, SVideoVO, VideoPureListVO, VideoPureVO, VideoVO

bp_resource = Blueprint('resource', __name__, url_prefix='/resource')


@bp_resource.route('/get', methods=['POST'])
def get_one():
    """ 通过传入ID进行获取资源 """
    form = ResourceByIDForm(check_token=True).check_validate()
    # @NOTE form.resource_type变量，来自TypeValidator校验器校验时挂载的
    if form.resource_type is RType.VIDEO:
        video = VideoService.get_by_id(form)
        return VideoVO(video).response()
    elif form.resource_type is RType.CHAPTER:
        chapter = ChapterService.get_by_id(form)
        return ChapterVO(chapter).response()
    elif form.resource_type is RType.COURSE:
        course = CourseService.get_by_id(form)
        return CourseVO(course).response()


@bp_resource.route('/gets/pure', methods=['POST'])
def gets():
    """ 获取某个用户独立的资源，也就是没有上一层级的资源，例如：只添加了单独的视频 """
    form = GetResourceListForm(check_token=True).check_validate()
    # @NOTE form.resource_type变量，来自TypeValidator校验器校验时挂载的
    if form.resource_type is RType.VIDEO:
        videos, pager = VideoService.gets(form)
        return VideoPureListVO(videos, pager).response()
    elif form.resource_type is RType.CHAPTER:
        chapters, pager = ChapterService.gets(form)
        return ChapterPureListVO(chapters, pager).response()
    elif form.resource_type is RType.COURSE:
        courses, pager = CourseService.gets(form)
        return CoursePureListVO(courses, pager).response()


# HTTPBasicAuthHandler

@bp_resource.route('/upload', methods=['POST'])
def upload_by_path():
    # 必须先Type校验,获取 resource_type
    type_form = TypeForm(check_token=True).check_validate()
    config_form = VSConfigForm().check_validate()
    # @NOTE form.resource_type变量，来自TypeValidator校验器校验时挂载的
    new_o = None
    if type_form.resource_type is RType.VIDEO:
        uf_form = UploadPureVideoForm(
            config_form, check_token=True).check_validate()
        new_o = VideoService.upload_by_file(uf_form)
    
    # @WAIT 下方的方法，将在下个版本中弃用，因为增加了vs-proxy服务。若引入批量上传，或将重构
    elif type_form.resource_type is RType.CHAPTER:
        uf_form = UploadByPathForm(
            check_token=True).check_validate()  # 自动进行token校验
        uf_form.vsConfigForm = config_form
        new_o = ChapterService.upload_by_path(uf_form)
    elif type_form.resource_type is RType.COURSE:
        uf_form = UploadByPathForm(
            check_token=True).check_validate()  # 自动进行token校验
        uf_form.vsConfigForm = config_form
        new_o = CourseService.upload_by_path(uf_form)
    return Success({
        'id': new_o.id,
        'name': new_o.name,
        'type': type_form.type.data,
        'config': dict(config_form.data),  # 需要测试
        'msg': '上传成功'
    }).response()


@bp_resource.route('/create/pure', methods=['POST'])
def create():
    """ 
        负责创建章节和课程目录
        @WAIT 后期可以改成，传入完整目录结构，直接生成，而不是现在需要通过多次的请求创建
        b.和c. 
        url: http://domain_url/v1/create/pure
        params:
            type:
            name: 资源的名称
        return:
            对应resource的id
    """
    form = CreateResourcePureForm(check_token=True).check_validate()
    r_type = RType(form.type.data)
    if r_type is RType.CHAPTER:
        chapter = ChapterService.create_pure(form)
        return CreatePureVO(chapter, r_type.value).response()
    if r_type is RType.COURSE:
        course = CourseService.create_pure(form)
        return CreatePureVO(course, r_type.value).response()
    return Forbidden('type: 取值只能为2或者3').response()


@bp_resource.route('/del', methods=['DELETE', 'POST'])
def del_resource():
    form = ResourceByIDForm(check_token=True).check_validate()
    # @NOTE form.resource_type变量，来自TypeValidator校验器校验时挂载的
    del_o = None
    if form.resource_type is RType.VIDEO:
        del_o = VideoService.del_by_id(form)
    elif form.resource_type is RType.CHAPTER:
        del_o = ChapterService.del_by_id(form)
    elif form.resource_type is RType.COURSE:
        del_o = CourseService.del_by_id(form)
    return Success(dict(
        id=del_o.id,
        name=del_o.name,
        type=form.type.data,
        msg='资源删除成功!'
    )).response()


@bp_resource.route('/update', methods=['PUT', 'POST'])
def put_resource():
    pass


@bp_resource.route("/search", methods=['POST'])
def search_by_key():
    form = SearchForm().check_validate()
    if form.resource_type is RType.VIDEO:
        return VideoService.searchByForm(form).response()
    elif form.resource_type is RType.CHAPTER:
        return ChapterService.searchByForm(form).response()
    elif form.resource_type is RType.COURSE:
        return CourseService.searchByForm(form).response()
    else:
        raise ServerError()


@bp_resource.route('/catalog', methods=['POST'])
def catalog():
    form = IDForm().check_validate()
    return VideoService.get_catalog(form).response()
